﻿using System;
using System.Net;
using NetCommand;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;
using NetCommand.Web;

namespace DtuService
{
    class HttpServer : IServer
    {
        public HttpService ServerApp;

        public HttpServer()
        {

        }
        
        /// <summary>
        /// 开启Htpp 监听
        /// </summary>
        public void StartHttp()
        {
            IPAddress address = IPAddress.Any;

            int port = 8000;
            int.TryParse(ServerMain.Instance.Config.AppSettings.Settings["httpPort"].Value, out port);
            int parallelNum = 0;
            int.TryParse(ServerMain.Instance.Config.AppSettings.Settings["ParallelNum"].Value, out parallelNum);
            int socketTimeOutMS = 0;
            int.TryParse(ServerMain.Instance.Config.AppSettings.Settings["SocketTimeOutMS"].Value, out socketTimeOutMS);

            ServerApp = new HttpService();
            if (!ServerApp.Setup(port))
            {
                Debug.Log("端口设置失败");
                return;
            }
            ServerApp.NewRequestReceived += ServerApp_NewRequestReceived;
            ServerApp.NewSessionConnected += ServerApp_NewSessionConnected;
            //启动服务  
            if (!ServerApp.Start())
            {
                Console.WriteLine("启动服务失败!");
                Console.ReadKey();
                return;
            }
            IPEndPoint listenPoint = new IPEndPoint(IPAddress.Any, port);

            Debug.LogDebug("Start http listen 0.0.0.0:" + port);
            WebMessageFactory.RegisterMessage();
        }

        private void ServerApp_NewSessionConnected(ByteSession session)
        {
            Debug.LogDebug("客户端连接 IP：" + session.IPAddress);
        }

        private void ServerApp_NewRequestReceived(ByteSession session, BinaryRequestInfo requestInfo)
        {
            Debug.LogDebug("收到消息： " + EncodingTools.outPut16Number(requestInfo.Body, requestInfo.Body.Length));
            HttpClient client = new HttpClient(session);
            client.ProcessReceive(requestInfo.Body, (object sender, string htm, string[] param)=>
            {
                HtmPage proc = (HtmPage)System.Activator.CreateInstance(Type.GetType(htm));

                if (proc == null)
                {
                    client.NotFound();
                }
                else
                {
                    CacheServer cacheServer = ServerMain.GetServer<CacheServer>();
                    if (cacheServer.SessionDintionary.ContainsKey(session.IPAddress) == false)
                    {// 给每一个Page的Session赋值， 同一个IP用同一个Session
                        Session _session = new Session();
                        _session.TimeStamp = ServerMain.Instance.CommonTools.GetTimeStamp();
                        cacheServer.SessionDintionary[session.IPAddress] = _session;
                    }
                    proc._Session = cacheServer.SessionDintionary[session.IPAddress];
                    proc.ProcessPage((HttpClient)sender, htm, param);
                    ServerMain.GetServer<CacheServer>().UpdateTokenTime(proc.Token);
                }
            });
        }
        
        public void Init()
        {
            StartHttp();
        }

        public void Tick(float deltaTime)
        {
            
        }

        public void ShutDown()
        {
            
        }
    }
}
